<template>
  <div class="app-container agreement">
    <div class="title">
      <div class="title_test">{{ title }}</div>
    </div>
    <div v-if="!showDialog">
      <el-row>
        <el-button type="primary" plain icon="Plus" @click="addProtocol()">添加协议</el-button>
      </el-row>
      <el-table v-loading="tableLoading" :data="tableData" highlight-current-row style="margin-top: 20px">
        <el-table-column label="ID" prop="agreementId" align="center" width="180" />
        <el-table-column prop="code" label="协议编码" align="center" />
        <el-table-column prop="title" label="协议名称" align="center" />
        <el-table-column prop="createTime" label="创建日期" align="center" />
        <el-table-column prop="createBy" label="创建人" align="center" />
        <el-table-column prop="updateTime" label="更新时间" align="center" />
        <el-table-column prop="updateBy" label="更新人" align="center" />
        <el-table-column fixed="right" label="操作" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="editProtocol(scope.row)"> 编辑 </el-button>
            <el-button link type="primary" @click="delectProtocol(scope.row)"> 删除 </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="listTotal" v-model:page="pageData.current" v-model:limit="pageData.size" @pagination="getTable" />
    </div>

    <el-form label-position="top" ref="formRef" :model="formData" v-if="showDialog">
      <div style="display: flex">
        <el-form-item
          label="协议标题"
          style="margin-right: 40px"
          prop="title"
          :rules="[{ required: true, message: '请输入协议标题', trigger: 'blur' }]"
        >
          <el-input v-model="formData.title" placeholder="请输入" style="width: 350px" />
        </el-form-item>
        <el-form-item label="协议编码" prop="code" :rules="[{ required: true, message: '请输入协议编码' }]">
          <el-input v-model="formData.code" placeholder="请输入" style="width: 350px" />
        </el-form-item>
      </div>

      <el-form-item
        label="协议内容"
        prop="content"
        :rules="[{ required: true, message: '请输入协议内容' }]"
        style="margin-bottom: 0px"
      >
      </el-form-item>
      <div style="border: 1px solid #ccc">
        <Toolbar style="border-bottom: 1px solid #ccc" :editor="editorRef" :defaultConfig="toolbarConfig" :mode="'default'" />
        <Editor
          style="height: 600px; overflow-y: hidden"
          v-model="formData.content"
          :defaultConfig="editorConfig"
          :mode="'simple'"
          @onCreated="handleCreated"
        />
      </div>
      <div class="btn-wrap">
        <el-button type="primary" @click="save">保存</el-button>
        <el-button type="primary" plain @click="cancel">取消</el-button>
      </div>
    </el-form>
  </div>
</template>
<script setup>
import { getPageservice, addserviceAgreement, editserviceAgreement, delectAgreement } from "@/api/system/rebateRules/protocol";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, ref, onBeforeUnmount } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
const formData = ref({});
// 搜索条件
const pageData = ref({
  introducerName: "",
  introducerNature: "",
  current: 1,
  size: 10
});
const formRef = ref(null);
const title = ref("协议配置");
//====================================富文本编辑器========================================================================================
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef();
// 内容 HTML
const toolbarConfig = {
  excludeKeys: ["group-image", "group-video", "emotion", "insertLink"] //配置不显示的菜单-上传图片、上传视频
  // toolbarKeys: ["bold"] //配置想要显示的菜单
};
const editorConfig = {
  placeholder: "请输入内容..."
};
const handleCreated = editor => {
  editorRef.value = editor; // 记录 editor 实例，重要！
};
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});
// 商家表格总数
const listTotal = ref(0);
// 表格数据
const tableData = ref([]);
const tableLoading = ref(false);
const showDialog = ref(false);
// 获取表格数据
const getTable = () => {
  tableLoading.value = true;
  getPageservice(pageData.value).then(res => {
    tableData.value = res.data.records;
    listTotal.value = res.data.total;
    tableLoading.value = false;
  });
};
const save = async () => {
  formRef.value.validate(async valid => {
    if (!valid) return false;

    if (formData.value.content === "<p><br></p>") {
      ElMessage({
        message: "请输入协议内容",
        type: "error"
      });
      return;
    }
    const isAddingAgreement = title.value === "添加协议";
    const performAction = isAddingAgreement ? addserviceAgreement : editserviceAgreement;
    try {
      const response = await performAction(formData.value);
      if (response.code === 200) {
        ElMessage({
          message: isAddingAgreement ? "添加成功" : "修改成功",
          type: "success"
        });
        getTable();
        showDialog.value = false;
        title.value = "协议配置";
        formData.value = {}; // 重置表单
      } else {
        ElMessage({
          message: isAddingAgreement ? "添加失败" : "修改失败",
          type: "error"
        });
      }
    } catch (error) {
      console.error("操作时出错:", error);
      ElMessage({
        message: "操作失败，请稍后重试",
        type: "error"
      });
    }
  });
};
const cancel = () => {
  formData.value = {};
  showDialog.value = false;
  title.value = "协议配置";
};
//增删改查
const addProtocol = () => {
  showDialog.value = true;
  title.value = "添加协议";
};
const editProtocol = row => {
  title.value = "修改协议";
  showDialog.value = true;
  formData.value = row;
};
const delectProtocol = row => {
  ElMessageBox.confirm(`请确认是否删除${row.title}协议？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const { code } = await delectAgreement(row);
    code == 200 &&
      ElMessage({
        message: "删除成功",
        type: "success"
      });
    getTable();
  });
};
getTable();
</script>
<style lang="scss" scoped>
.agreement {
  position: relative;
  .btn-wrap {
    position: absolute;
    right: 20px;
    top: 60px;
  }
}
.title {
  margin-left: -20px;
  margin-right: -20px;
  margin-bottom: 20px;
  border-bottom: 1px solid #dae2ef;
  .title_test {
    padding-left: 40px;
    font-weight: 500;
    font-size: 18px;
    padding-bottom: 10px;
    position: relative;
    &::before {
      position: absolute;
      content: "";
      width: 6px;
      height: 6px;
      border-radius: 50%;
      background-color: #409eff;
      top: 6px;
      left: 20px;
    }
  }
}
</style>
